package org.sgs.toolbox.sql;

import javax.sql.DataSource;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.SqlRowSetResultSetExtractor;
import org.springframework.jdbc.support.rowset.ResultSetWrappingSqlRowSet;

public class SqlUtils {
	
	private static JdbcTemplate jdbcTemplate;
	static {
		ApplicationContext ac = new ClassPathXmlApplicationContext("context.xml");
	    DataSource dataSource = (DataSource) ac.getBean("dataSource");
	    jdbcTemplate = new JdbcTemplate(dataSource);
	}

	public static int queryForInt(String sql) throws DataAccessException {
		return jdbcTemplate.queryForInt(sql);
	}
	
	public static GenericRecordList queryForList(String sql) throws DataAccessException {
		ResultSetWrappingSqlRowSet rowSet = (ResultSetWrappingSqlRowSet) jdbcTemplate.query(sql, new SqlRowSetResultSetExtractor());
		return new GenericRecordList(rowSet);
	}

}
